
import time
from src import common
from utils.initApp import mysql


class UserService:
    def __init__(self, describe):
        self.totalStorage = 10 * 1024 * 1024 * 1024
        self.user_describe = describe
        return

    def __construct_user_info(self, user):

        data = dict()
        data['userName'] = user['userName']
        data['userId'] = user['userId']
        data['time'] = str(time.time())

        info = dict()
        info['token'] = common.construct_token(data)
        # add_user_token(_data['username'], _data['token'])
        return info

    def list_all(self):
        result = mysql.list_all_filter('user', self.user_describe)
        return result

    def avatar(self, values):
        user = mysql.get('user', values, cur_key='userId')
        sql = "SELECT SUM(size) AS size FROM files WHERE userId='%s'" % values['userId']
        data = mysql.customize_sql(sql)

        result = dict()
        result['avatar'] = user['avatar']
        result['storage'] = int(data[0]['size'])
        result['totalStorage'] = self.totalStorage

        return result

    def get(self, values):
        user = mysql.get('user', values, cur_key='userId')
        print(user)
        result = common.filter_key(user, self.user_describe)
        print(result)
        return result

    def update(self, values):
        result = mysql.update("user", values, cur_key="userId")
        return result

    def reset(self, values):
        sha256_old_password = common.make_sha256(values['oldPassword'])
        sha256_new_password = common.make_sha256(values['newPassword'])

        user = mysql.get('uesr', values)

        if user['password'] == sha256_old_password:
            data = dict()
            data['userId'] = values['userId']
            data['password'] = sha256_new_password
            user = mysql.update('uesr', data)
            return {}, '修改成功', 0
        else:
            return {}, '旧密码输入有误', -1
